package com.fowo.api.common.util;

import com.baomidou.mybatisplus.extension.service.IService;
import com.fowo.api.common.entity.IdObject;
import com.fowo.api.common.model.BatchSaveModal;
import lombok.experimental.UtilityClass;

import javax.swing.plaf.DesktopIconUI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@UtilityClass
public class ServiceUtils {

    /**
     * 批量保存操作
     * @apiNote 此代码不包括事务块，请在事务上下文内调用
     * @param modals
     * @param <T>
     * @return 返回新建的 id 对应关系，键为提交时 id, 值为入库真实 id
     */
    public <T extends IdObject> Map<Long, Long> batchSave(BatchSaveModal<T> modals, IService<T> service) {
        if (modals == null || modals.getItems() == null) {
            return null;
        }
        Map<Long, Long> tempIdMap = new TreeMap<>();
        List<Long> needRemoveIds = new ArrayList<>(modals.getIds());
        for (T item: modals.getItems()) {
            if(item.getId() == null || !modals.getIds().contains(item.getId())) {
                // 新增
                final Long tmpId = item.getId();
                item.setId(null);
                service.save(item);
                if (tmpId != null) {
                    tempIdMap.put(tmpId, item.getId());
                }

            } else {
                // 更新
                service.updateById(item);
                needRemoveIds.remove(item.getId());
            }
        }
        if (!needRemoveIds.isEmpty()) {
            // 删除
            needRemoveIds.forEach(service::removeById);
        }
        return tempIdMap;
    }
}
